package ch7.BTree;

public class BTreeOrder {
    public static void PreOrder1(BTreeClass bt) {  //先序遍历的递归算法
        PreOrder11(bt.b);
    }

    private static void PreOrder11(BTNode<Character> t) {  //被PreOrder1方法调用
        if (t != null) {
            System.out.print(t.data + " ");
            PreOrder11(t.lchild);
            PreOrder11(t.rchild);
        }
    }

    public static int nodeCount1(BTreeClass bt) {  //先序遍历的递归算法
        return nodeCount11(bt.b);
    }

    private static int nodeCount11(BTNode<Character> t) {  //被PreOrder1方法调用
        int i, j, k;
        if (t != null) {
            i = 1;
            j = nodeCount11(t.lchild);
            k = nodeCount11(t.rchild);
            return i + j + k;
        }
        return 0;
    }
    public static void main(String[] args) {
        String s = "A(B(D(,G)),C(E,F))";
        //String s = "A(B,C(D))";
        BTreeClass bt = new BTreeClass();
        bt.CreateBTree(s);
        System.out.println("bt: " + bt);

        BTreeOrder treeOrder = new BTreeOrder();
        System.out.print("递归先序遍历序列: ");
        //treeOrder.PreOrder1(bt);
        BTreeOrder.PreOrder1(bt);
        System.out.println();

        System.out.print("结点个数: ");
        int count = BTreeOrder.nodeCount1(bt);
        System.out.println(count);

        System.out.print("递归后序遍历序列: ");
        treeOrder.PostOrder1(bt);
        System.out.println();
    }

    public void InOrder1(BTreeClass bt) {  //中序遍历的递归算法
        InOrder11(bt.b);
    }

    private void InOrder11(BTNode<Character> t) {   //被InOrder1方法调用
        if (t != null) {
            InOrder11(t.lchild);                //中序遍历左子树
            System.out.print(t.data + " ");     //访问根结点
            InOrder11(t.rchild);                //中序遍历右子树
        }
    }

    public void PostOrder1(BTreeClass bt) {  //后序遍历的递归算法
        PostOrder11(bt.b);
    }

    private void PostOrder11(BTNode<Character> t) { //被PostOrder1方法调用
        if (t != null) {
            PostOrder11(t.lchild);              //后序遍历左子树
            PostOrder11(t.rchild);              //后序遍历右子树
            System.out.print(t.data + " ");     //访问根结点
        }
    }
}
